# -*- coding: utf-8 -*-
from __future__ import print_function
import Tkinter as tk
import ttk
import rospy  # ROS
from std_msgs.msg import String  # ROS 话题消息格式


class ChemicalGUI(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.title(u"化学试剂自动搬运系统 - 界面")
        self.geometry("750x500")

        # -----------------------------
        # 1. ROS 初始化
        # -----------------------------
        rospy.init_node("chemical_gui_publisher", anonymous=True)
        self.ros_publisher = rospy.Publisher("chemical_task", String, queue_size=10)
        rospy.Subscriber("task_status", String, self.ros_callback)

        self.task_running = False  # 任务状态标志
        self.task_counter = 0  # 控制发送 5 次

        # -----------------------------
        # 2. 数据 & 变量
        # -----------------------------
        self.item_stations = [1,2,3]
        self.place_stations = [1,2,3]
        self.chemicals = [1,2,3,4,5,6,]

        # -----------------------------
        # 3. 主界面布局
        # -----------------------------
        left_frame = ttk.Labelframe(self, text=u"操作面板")
        left_frame.pack(side=tk.LEFT, fill=tk.Y, padx=10, pady=10)

        right_frame = ttk.Frame(self)
        right_frame.pack(side=tk.RIGHT, fill=tk.BOTH, expand=True, padx=10, pady=10)

        # 右侧数据表格
        table_frame = ttk.Labelframe(right_frame, text=u"数据表格")
        table_frame.pack(fill=tk.BOTH, expand=True)

        self.table = ttk.Treeview(table_frame, columns=(u"步骤", u"详情"), show="headings", height=12)
        self.table.heading(u"步骤", text=u"步骤")
        self.table.heading(u"详情", text=u"详情")
        self.table.column(u"步骤", width=50, anchor="center")
        self.table.column(u"详情", width=500, anchor="center")
        self.table.pack(fill=tk.BOTH, expand=True)

        # 右侧操作日志
        log_frame = ttk.Labelframe(right_frame, text=u"操作日志")
        log_frame.pack(fill=tk.BOTH, expand=True, pady=10)
        self.log_text = tk.Text(log_frame, height=10)
        self.log_text.pack(fill=tk.BOTH, expand=True)

        # -----------------------------
        # 4. 左侧操作面板布局
        # -----------------------------
        ttk.Label(left_frame, text=u"选择物品台:").pack(anchor="w", pady=(10, 0), padx=5)
        self.item_cmb = ttk.Combobox(left_frame, values=self.item_stations, state="readonly")
        self.item_cmb.current(0)
        self.item_cmb.pack(anchor="w", padx=5, pady=5)

        ttk.Label(left_frame, text=u"选择放置台:").pack(anchor="w", pady=(10, 0), padx=5)
        self.place_cmb = ttk.Combobox(left_frame, values=self.place_stations, state="readonly")
        self.place_cmb.current(0)
        self.place_cmb.pack(anchor="w", padx=5, pady=5)

        ttk.Label(left_frame, text=u"选择化学试剂:").pack(anchor="w", pady=(10, 0), padx=5)
        self.chem_cmb = ttk.Combobox(left_frame, values=self.chemicals, state="readonly")
        self.chem_cmb.current(0)
        self.chem_cmb.pack(anchor="w", padx=5, pady=5)

        # 按钮
        btn_frame = ttk.Frame(left_frame)
        btn_frame.pack(anchor="center", pady=10)
        self.start_btn = ttk.Button(btn_frame, text=u"开始执行", command=self.start_task)
        self.start_btn.pack(side=tk.LEFT, padx=5)
        self.cancel_btn = ttk.Button(btn_frame, text=u"取消任务", command=self.cancel_task)
        self.cancel_btn.pack(side=tk.LEFT, padx=5)

    # -----------------------------
    # 5. 任务控制
    # -----------------------------
    def start_task(self):
        """ 开始任务，显示步骤并持续发送 ROS 话题 """
        if self.task_running:
            return  # 防止重复启动任务

        self.task_running = True
        self.task_counter = 0  # 任务计数器重置
        self.log(u"任务开始...")

        # **显示任务步骤**
        self.update_table()

        # **开始循环发送**
        self.publish_task()

    def update_table(self):
        """ 显示任务步骤 """
        item_station = self.item_cmb.get()
        place_station = self.place_cmb.get()
        chemical = self.chem_cmb.get()

        # 清空表格
        self.table.delete(*self.table.get_children())

        steps = [
            (u"1", u"小车启动，前往 物品台{}".format(item_station)),
            (u"2", u"机械臂抓取 目标{}".format(chemical)),
            (u"3", u"小车移动，前往 放置台{}".format(place_station)),
            (u"4", u"机械臂放置 目标{}".format(chemical)),
            (u"5", u"返回初始位置")
        ]
        for step in steps:
            self.table.insert("", tk.END, values=step)

    def publish_task(self):
        """ 持续发送任务数据 5 秒 """
        if not self.task_running or self.task_counter >= 500:
            return  # 若任务已结束或已发送 5 次，停止

        # item_station = str(self.item_cmb.get().decode("utf-8"))
        item_station = self.item_cmb.get()
        place_station = self.place_cmb.get()
        chemical = self.chem_cmb.get()

        print(item_station, place_station, chemical)
        # item_station = str(item_station)
        # if item_station == "物品台":
        #     print("1")
        print(type(item_station))

        ros_message = "[{}, {}, {}]".format(item_station, place_station, chemical)
        # ros_message = [item_station, place_station, chemical]
        self.ros_publisher.publish(ros_message)
        if self.task_counter == 0:
            self.log(u"ROS 发布: " + ros_message)

        self.task_counter += 1

        # 1 秒后继续发送
        self.after(10, self.publish_task)

    def ros_callback(self, msg):
        """ 监听 ROS 任务状态，当收到 'done' 时停止任务 """
        if msg.data == "done":
            self.task_running = False
            self.log(u"任务结束")

    def cancel_task(self):
        """ 手动取消任务 """
        self.task_running = False
        self.log(u"任务已被手动取消。")

    def log(self, content):
        """ 记录日志 """
        self.log_text.insert(tk.END, content + "\n")
        self.log_text.see(tk.END)


def main():
    app = ChemicalGUI()
    app.mainloop()


if __name__ == "__main__":
    main()
